﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Diagnostics;

namespace Meteorite
{
    interface Obj
    { 
        //public virtual void Draw()
    }
    public class Entity : Moveable
    {
        public Model model { get; set; }
        


        public float Scale
        {
            get { return scale; }
            set { scale = value; }
        }
        float scale;

        public Matrix World
        {
            get { return world; }
        }
        protected Matrix world;
        
        public Entity(Model model)
        {
            this.model = model;
        }
        public Vector3 Rotation
        {
            get { return rotation; }
            set { rotation = value; }
        }
        protected Vector3 rotation = Vector3.Zero;

        public Vector3 RotationSpeed
        {
            get { return rotationSpeed; }
            set { rotationSpeed = value; }
        }
        protected Vector3 rotationSpeed = Vector3.Zero;

        public virtual void Draw(Matrix View, Matrix Projection)
        {
            Matrix[] transforms = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(transforms);

            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.World = transforms[mesh.ParentBone.Index] * world;

                    effect.View = View;
                    effect.Projection = Projection;
                }
                mesh.Draw();
            }
        }
        public void CalculateWorld()
        {
            world = Matrix.Identity;
            world *= Matrix.CreateScale(Scale);
            world *= Matrix.CreateFromYawPitchRoll(Rotation.X, Rotation.Y, Rotation.Z);
            world *= Matrix.CreateTranslation(Position);
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
            Rotation += RotationSpeed;
            CalculateWorld();
        }

        public bool CheckCollision(Entity entity)
        {
            Model model2 = entity.model;
            Matrix world2 = entity.World;

            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (ModelMesh mesh2 in model2.Meshes)
                {
                    // 每个 ModelMesh 对象都有一个 BoundingSphere 属性
                    if (mesh.BoundingSphere.Transform(World).Intersects(mesh2.BoundingSphere.Transform(world2)))
                        return true;
                }

            }

            return false;

        }
    }
}
